﻿using System.Linq;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using SimpleServiceBus.Bus;
using SimpleServiceBus.Bus.Subscriptions;

namespace SimpleServiceBus.Tests.Bus.Subscriptions
{
    [TestFixture]
    public class MessageTypeSubscriptionTestFixture
    {
        [Test]
        public void Can_Add_And_Remove_Subscribers()
        {
            var sub = new MessageTypeSubscription(typeof (int), "one", "two", "three");
            sub.RemoveSubscribers("two", "three");
            sub.AddSubscribers("four", "five");

            Assert.That(sub.Subscribers.Length, Is.EqualTo(3));
            Assert.That(sub.Subscribers.Contains("one"));
            Assert.That(sub.Subscribers.Contains("four"));
            Assert.That(sub.Subscribers.Contains("five"));

            sub = new MessageTypeSubscription(typeof (bool));
            sub.AddSubscribers("one", "two");
            sub.RemoveSubscribers("one");
            sub.AddSubscribers("meat", "potatoes");
            sub.RemoveSubscribers("meat");

            Assert.That(sub.Subscribers.Length, Is.EqualTo(2));
            Assert.That(sub.Subscribers.Contains("two"));
            Assert.That(sub.Subscribers.Contains("potatoes"));
        }

        [Test]
        public void Constructor_Pre_Loads_Subscribers_And_Predicate()
        {
            var sub = new MessageTypeSubscription(typeof (string), "one", "two", "three");

            Assert.That(sub.Subscribers.Length, Is.EqualTo(3));

            Assert.That(sub.Subscribers.Contains("one"));
            Assert.That(sub.Subscribers.Contains("two"));
            Assert.That(sub.Subscribers.Contains("three"));

            Assert.That(sub.Matches(new MessageEnvelope {Body = "hi"}), Is.True);
            Assert.That(sub.Matches(new MessageEnvelope {Body = 1}), Is.False);
        }

        [Test]
        public void Multiple_Subscriptions_From_Subscriber_Results_In_Single_Subscription()
        {
            var sub = new MessageTypeSubscription(typeof (string), "one", "one", "one");
            sub.AddSubscribers("one", "one");

            Assert.That(sub.Subscribers.Length, Is.EqualTo(1));

            sub.RemoveSubscribers("one");

            Assert.That(sub.Subscribers.Length, Is.EqualTo(0));
        }
    }
}